package com.jk.vehicle.core.utils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.jk.vehicle.core.entity.Adcode;
import com.jk.vehicle.core.entity.Address;
import com.jk.vehicle.core.entity.GaoDeDistance;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 高德api工具类
 * @author: jiajiang
 * @date: 2021/03/03
 */
@Slf4j
public class GaoDeMapUtil {

    private static Logger logger=LoggerFactory.getLogger(GaoDeMapUtil.class);

    /**
     * 高德api key
     */
    private final static String key = "0607899bebd24c4d9ddae885064b3cf7";
    // private static String key = "16614ab1ffce9c783e8c5de31efc6378";

    private final  static String STATUS_OK = "1";

    /**
     * 高德api 根据经纬度获取地址
     *
     * @param log
     * @param lat
     * @return
     */
    public static String getAdd(String log, String lat) {
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&location=").append(log).append(",").append(lat);
        String res = sendPost("http://restapi.amap.com/v3/geocode/regeo", s.toString());
        logger.info(res);
        JSONObject jsonObject = JSONObject.fromObject(res);
        JSONObject jsonObject1 = JSONObject.fromObject(jsonObject.get("regeocode"));
        String add = jsonObject1.get("formatted_address").toString();
        return add;
    }

    /**
     * 高德api 根据经纬度获取所在城市
     *
     * @param log
     * @param lat
     * @return
     */
    public static String getCity(String log, String lat) {
        // log 大 lat 小
        // 参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
        String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + lat + "," + log + "&type=010";
        String res = "";
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream
                    (), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line + "\n";
            }
            in.close();
            JSONObject jsonObject = JSONObject.fromObject(res);
            JSONArray jsonArray = JSONArray.fromObject(jsonObject.getString("addrList"));
            JSONObject j_2 = JSONObject.fromObject(jsonArray.get(0));
            String allAdd = j_2.getString("admName");
            String arr[] = allAdd.split(",");
            res = arr[1];
        } catch (Exception e) {
            logger.info("error in wapaction,and e is " + e.getMessage());
        }
        logger.info(res);
        return res;
    }

    /**
     * 高德api 根据地址获取经纬度
     *
     * @param name
     * @return
     */
    public static String getLatAndLogByName(String name) {
        StringBuffer s = new StringBuffer();
        s.append("key=" + key + "&address=" + name);
        String res = sendPost("http://restapi.amap.com/v3/geocode/geo", s.toString());
        logger.info(res);
        JSONObject jsonObject = JSONObject.fromObject(res);
        JSONArray jsonArray = JSONArray.fromObject(jsonObject.getString("geocodes"));
        JSONObject location = (JSONObject) jsonArray.get(0);
        String add = location.get("location").toString();
        return add;
    }

    /**
     * 高德api 坐标转换---转换至高德经纬度
     * @param log
     * @param lat
     * @param type
     * @return
     */
    public static String convertLocations(String log, String lat, String type) {
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&locations=").append(log).append(",").append(lat).append("&coordsys=");
        if (type == null) {
            s.append("gps");
        } else {
            s.append(type);
        }
        String res = sendPost("http://restapi.amap.com/v3/assistant/coordinate/convert", s.toString());
        logger.info(res);
        JSONObject jsonObject = JSONObject.fromObject(res);
        String add = jsonObject.get("locations").toString();
        return add;
    }

    /**
     * 通过名称获取地址
     *
     * @param name
     * @return
     */
    public static String getAddByName(String name) {
        // log 大 lat 小
        // 参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
        String urlString = "http://gc.ditu.aliyun.com/geocoding?a=" + name;
        String res = "";
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line + "\n";
            }
            in.close();
            JSONObject jsonObject = JSONObject.fromObject(res);
            String lon = jsonObject.getString("lon");
            String lat = jsonObject.getString("lat");
            System.err.println(jsonObject);
            res = getNearbyAdd(lon, lat);
        } catch (Exception e) {
            logger.info("error in wapaction,and e is " + e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 通过经纬度获取附近
     *
     * @param log
     * @param lat
     * @return
     */
    public static String getNearbyAdd(String log, String lat) {

        String add = sendGet("http://ditu.amap.com/service/regeo", "longitude=" + log + "&latitude=" + lat +
                "&type=010");

        logger.info(add);

        return add;
    }

    /**
     * 高德api 关键字模糊查询
     *
     * @param keyWord
     * @param city
     * @return
     */
    public static String getKeywordsAddByLbs(String keyWord, String city) {
        StringBuffer s = new StringBuffer();
        s.append("key=" + key + "&keywords=");
        if (keyWord.contains(" ")) {
            String[] str = keyWord.split(" ");
            for (int i = 0; i < str.length; i++) {
                if (i == 0) {
                    s.append(str[i]);
                } else {
                    s.append("+" + str[i]);
                }
            }
        } else {
            s.append(keyWord);
        }
        s.append("&city=" + city);
        s.append("offset=10&page=1");
        String around = sendPost("http://restapi.amap.com/v3/place/text", s.toString());
        logger.info(around);
        return around;
    }

    /**
     * 高德api 经纬度/关键字 附近地标建筑及地点查询
     *
     * @param log
     * @param lat
     * @param keyWord
     * @return
     */
    public static String getAroundAddByLbs(String log, String lat, String keyWord) {
        String around = sendPost("http://restapi.amap.com/v3/place/around",
                "key=" + key + "&location=" + log + "," + lat + "&keywords=" + keyWord +
                        "&radius=2000&offset=10&page=1");
        logger.info(around);
        return around;
    }

    /**
     * 发送Get请求
     * @param url
     * @param param
     * @return
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                logger.info(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * GET请求数据
     *
     * @param get_url url地址
     * @param content key=value形式
     * @return 返回结果
     * @throws Exception
     */
    public static String sendGetData(String get_url, String content) throws Exception {
        String result = "";
        URL getUrl = null;
        BufferedReader reader = null;
        String lines = "";
        HttpURLConnection connection = null;
        try {
            if (content != null && !content.equals(""))
                get_url = get_url + "?" + content;
            // get_url = get_url + "?" + URLEncoder.encode(content, "utf-8");
            getUrl = new URL(get_url);
            connection = (HttpURLConnection) getUrl.openConnection();
            connection.connect();
            // 取得输入流，并使用Reader读取
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码
            while ((lines = reader.readLine()) != null) {
                result = result + lines;
            }
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            if (reader != null) {
                reader.close();
                reader = null;
            }
            connection.disconnect();
        }
    }

    /**
     * @param POST_URL url地址
     * @param content  key=value形式
     * @return 返回结果
     * @throws Exception
     */
    public static String sendPostData(String POST_URL, String content) throws Exception {
        HttpURLConnection connection = null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        String line = "";
        String result = "";
        try {
            URL postUrl = new URL(POST_URL);
            connection = (HttpURLConnection) postUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            // Post 请求不能使用缓存
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.connect();

            out = new DataOutputStream(connection.getOutputStream());
            // content = URLEncoder.encode(content, "utf-8");
            // DataOutputStream.writeBytes将字符串中的16位的unicode字符�?8位的字符形式写道流里�?
            out.writeBytes(content);
            out.flush();
            out.close();
            // 获取结果
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编码
            while ((line = reader.readLine()) != null) {
                result = result + line;
            }
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }
            if (reader != null) {
                reader.close();
                reader = null;
            }
            connection.disconnect();
        }
    }

    /**
     * 过滤掉html里不安全的标签，不允许用户输入这些标签
     * @param inputString
     * @return
     */
    public static String htmlFilter(String inputString) {
        // return inputString;
        String htmlStr = inputString; // 含html标签的字符串
        String textStr = "";
        Pattern p_script;
        java.util.regex.Matcher m_script;

        try {
            String regEx_script = "<[\\s]*?(script|style)[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?(script|style)[\\s]*?>";
            String regEx_onevent = "on[^\\s]+=\\s*";
            String regEx_hrefjs = "href=javascript:";
            String regEx_iframe = "<[\\s]*?(iframe|frameset)[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?(iframe|frameset)" +
                    "[\\s]*?>";
            String regEx_link = "<[\\s]*?link[^>]*?/>";

            htmlStr = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
            htmlStr = Pattern.compile(regEx_onevent, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
            htmlStr = Pattern.compile(regEx_hrefjs, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
            htmlStr = Pattern.compile(regEx_iframe, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
            htmlStr = Pattern.compile(regEx_link, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");

            textStr = htmlStr;

        } catch (Exception e) {
            System.err.println("Html2Text: " + e.getMessage());
        }

        return textStr;
    }

    /**
     * 根据地址获取经纬度
     * @param address
     * @return
     */
    public static String getLonLat(String address){
        //返回输入地址address的经纬度信息, 格式是 经度,纬度
        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key="+key+"&address="+address;
        String queryResult = sendGet(queryUrl,"");  //高德接品返回的是JSON格式的字符串
        JSONObject jo = JSONObject.fromObject(queryResult);
        JSONArray ja = jo.getJSONArray("geocodes");
        JSONObject.fromObject(ja.getString(0)).get("location");
        return JSONObject.fromObject(ja.getString(0)).get("location").toString();
    }

    /**
     * 使用高德API接口查询两个地址之间的距离
     * 获取一个地址的经度、纬度信息
     * 通过两个地址的经纬度，查询距离
     * @param startLonLat
     * @param endLonLat
     * @return
     */
    public static Long getDistance(String startLonLat, String endLonLat){
        //返回起始地startAddr与目的地endAddr之间的距离，单位：米
        Long result = new Long(0);
        String queryUrl = "http://restapi.amap.com/v3/distance?key="+key+"&origins="+startLonLat+"&destination="+endLonLat;
        // String queryResult = getResponse(queryUrl);
        String queryResult = sendGet(queryUrl, "");
        JSONObject jo = new JSONObject().fromObject(queryResult);
        JSONArray ja = jo.getJSONArray("results");

        result = Long.parseLong(new JSONObject().fromObject(ja.getString(0)).get("distance").toString());
        return result;
        // return queryResult;
    }

    /**
     * 根据经纬度、类型获取距离
     * @param startLonLat
     * @param endLonLat
     * @param type
     * @return
     */
    public static List<Map<String, Object>> getDistanceResult(String startLonLat, String endLonLat,String type){
        String queryUrl = "http://restapi.amap.com/v3/distance?key="+key+"&origins="+startLonLat+"&destination="+endLonLat;
        if (type != null) {
            queryUrl=queryUrl+"&type="+type;
        }
        String queryResult = sendGet(queryUrl,"");
        JSONObject jo = new JSONObject().fromObject(queryResult);
        List<GaoDeDistance> list = JSON.parseArray(jo.getString("results"), GaoDeDistance.class);
        List<Map<String, Object>> mapList = BeanUtils.beansToMaps(list);
        return mapList;
    }

    /**
     * 根据起始点经纬度获取预估行驶时间和预估里程(第一条)
     * @param startLon
     * @param startLat
     * @param endLon
     * @param endLat
     * @return duration预估行驶时间s，distance预估距离m
     */
    public static Map<String,Object> getDurationAndDistance(String startLon, String startLat, String endLon, String endLat) {
        //将起点经纬转化为高德经纬
        String gaoDeLonLat = GaoDeMapUtil.convertLocations(startLon,startLat,"1");
        //将终点经纬转化为高德经纬
        String gaoDeDestinationLonLat = GaoDeMapUtil.convertLocations(endLon,endLat,"1");
        //调用高德API获取预估行驶时间和预估距离
        List<Map<String, Object>> maps;
        Map<String, Object> distanceResult=null;
        try {
            maps = GaoDeMapUtil.getDistanceResult(gaoDeLonLat, gaoDeDestinationLonLat, "1");
            distanceResult= maps.get(0);
        } catch (Exception e) {
            logger.error("高德规划异常，请检查入参重试！");
        }
        if (distanceResult.containsKey("info") &&distanceResult.get("info")!=null&&distanceResult.get("info").toString().equals("OK")) {
            return distanceResult;
        } else {
            try {
                maps = GaoDeMapUtil.getDistanceResult(gaoDeLonLat, gaoDeDestinationLonLat, "0");
                distanceResult = maps.get(0);
            } catch (Exception e) {
                logger.error("高德规划异常，请检查入参重试！");
            }
            return distanceResult;
        }
        /*if (distanceResult.containsKey("info") && distanceResult.get("info") != null) {
                return ReturnEntity.failedResult(distanceResult.get("info").toString());
            } else if (distanceResult.containsKey("code")&&distanceResult.get("code")!=null) {
                String code = distanceResult.get("code").toString();
                switch (code){
                case "1":
                    return ReturnEntity.failedResult("指定地点之间没有可以行车的道路");
                case "2":
                    return ReturnEntity.failedResult("起点/终点 距离所有道路均距离过远（例如在海洋/矿业）");
                case "3":
                    return ReturnEntity.failedResult("起点/终点不在中国境内");
            }
        }*/
    }

    /**
     * 根据地址获取区编码
     * @return
     */
    public static Map<String, Object> getGaodeAdcodeByAddress(String address) {
        Map<String, Object> mapResult = new HashMap<>();
        String provinceCityAreaStr = HttpKit.get("https://restapi.amap.com/v3/geocode/geo?key=" + key + "&address=" + address + "");
        com.alibaba.fastjson.JSONObject provinceCityArea = com.alibaba.fastjson.JSONObject.parseObject(provinceCityAreaStr);
        if (provinceCityArea!=null&&STATUS_OK.equals(provinceCityArea.getString("status"))) {
            com.alibaba.fastjson.JSONObject geocodes = provinceCityArea.getJSONArray("geocodes").getJSONObject(0);
            mapResult.put("adcode", geocodes.getString("adcode"));
            mapResult.put("citycode", geocodes.getString("citycode"));
        }
        return mapResult;
    }

    /**
     * 根据经纬度获取省市区的编码
     * @param lng 经度
     * @param lat 纬度
     * @return
     */
    public static Adcode getAdcode(String lng, String lat){
        Adcode adcode=new Adcode();

        Address address=getAddress(lng,lat);
        String province=address.getProvicne();
        String city=address.getCity();
        String district=address.getDistrict();
        String township=address.getTownship();

        //获取省份的编码
        String proMessage=getCodeResponse("https://restapi.amap.com/v3/geocode/geo?address="+province+"&key="+key+"");
        JSONObject proObject=JSONObject.fromObject(proMessage);
        JSONArray proArray=proObject.getJSONArray("geocodes");
        if (proArray.size()>0) {
            JSONObject proObject2=proArray.getJSONObject(0);
            String proCode=proObject2.getString("adcode");
            adcode.setProvicneCode(proCode);
        }

        //获取市区的编码
        String cityMessage=getCodeResponse("https://restapi.amap.com/v3/geocode/geo?address="+city+"&key="+key+"");
        JSONObject cityObject=JSONObject.fromObject(cityMessage);
        JSONArray cityArray=cityObject.getJSONArray("geocodes");
        if (cityArray.size()>0) {
            JSONObject cityObject2=cityArray.getJSONObject(0);
            String cityCode=cityObject2.getString("adcode");
            adcode.setCityCode(cityCode);
        }

        //获取市区的编码
        String disMessage=getCodeResponse("https://restapi.amap.com/v3/geocode/geo?address="+district+"&key="+key+"");
        JSONObject disObject=JSONObject.fromObject(disMessage);
        JSONArray disArray=disObject.getJSONArray("geocodes");
        if (disArray.size()>0) {
            JSONObject disObject2=disArray.getJSONObject(0);
            String disCode=disObject2.getString("adcode");
            adcode.setDistrictCode(disCode);
        }

        //获取街道的编码
        String townMessage=getCodeResponse("https://restapi.amap.com/v3/geocode/geo?address="+township+"&key="+key+"");
        JSONObject townObject= JSONObject.fromObject(townMessage);
        JSONArray townArray=townObject.getJSONArray("geocodes");
        if (townArray.size()>0) {
            JSONObject townObject2=townArray.getJSONObject(0);
            String townCode=townObject2.getString("adcode");
            adcode.setTownshipCode(townCode);
        }

        return adcode;
    }

    /**
     *  根据经纬度获取省市区
     * @param lng 经度
     * @param lat 纬度
     * @return
     */
    public static Address getAddress(String lng, String lat){
        Address address=new Address();
        String allMessage=getAddressResponse("https://restapi.amap.com/v3/geocode/regeo?location="+lng+","+lat+"&key="+key+"&radius=1000&extensions=all");
        JSONObject jsonObject= JSONObject.fromObject(allMessage);
        JSONObject object=jsonObject.getJSONObject("regeocode");
        JSONObject addressMessage=object.getJSONObject("addressComponent");

        String province=addressMessage.getString("province");
        String city=addressMessage.getString("city");
        String district=addressMessage.getString("district");
        String township=addressMessage.getString("township");
        String disCode=addressMessage.getString("adcode");

        address.setProvicne(province);
        address.setCity(city);
        address.setDistrict(district);
        address.setTownship(township);

        return address;
    }

    /**
     * 根据经纬度获取城市编码
     * @param lng
     * @param lat
     * @return
     * @throws IOException
     */
    public static String getCoordinate(String lng, String lat) throws IOException {
        StringBuilder resultData = new StringBuilder();
        StringBuilder https = new StringBuilder("http://restapi.amap.com/v3/geocode/regeo?key=");
        //经纬度地址
        StringBuilder localhost = new StringBuilder("&location=" + lng + "," + lat);
        StringBuilder httpsTail = new StringBuilder("&poitype=&radius=&extensions=base&batch=true");
        String url = https.append(key).append(localhost).append(httpsTail).toString();
        //拼接出来的地址
        //System.out.println(https1.append(key).append(localhost1).append(httpsTail).toString());
        // String url ="http://restapi.amap.com/v3/geocode/regeo?key=自己申请的key&location=116.310003,39.991957&poitype=&radius=&extensions=base&batch=true&roadlevel=";
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStreamReader insr = null;
        BufferedReader br = null;
        try {
            httpsConn = myURL.openConnection();// 不使用代理
            if (httpsConn != null) {
                insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
                br = new BufferedReader(insr);
                String data = null;
                while ((data = br.readLine()) != null) {
                    resultData.append(data);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (insr != null) {
                insr.close();
            }
            if (br != null) {
                br.close();
            }
        }
        if (resultData.toString().indexOf("regeocodes") == 0) {
            return null;
        }
        String str = JSONObject.fromObject(resultData.toString()).getString("regeocodes");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("province", provinceName(str)); // 省
        jsonObject.put("city", cityName(str)); // 城市名称
        jsonObject.put("citycode", cityCode(str)); // 城市编码
        jsonObject.put("district", adName(str)); // 区名称
        jsonObject.put("adcode", adCode(str)); // 区编码
        return jsonObject.toString();
    }

    /**
     * 获取省名称
     * @return
     */
    public static String provinceName(String str) {
        //省切割
        String[] strr = str.split("\",\"province\":\"");
        if (strr.length < 2 && strr.length == 1) {
            //直辖市
            String[] sr = str.split("\"province\":\"");
            String[] srr = sr[1].split("\",\"province");
            return srr[0];
        }
        //非直辖市
        String[] strrr = strr[1].split("\",\"city\":");
        return strrr[0];
    }

    /**
     * 获取城市名称
     * @return
     */
    public static String cityName(String str) {
        //城市切割
        String[] strr = str.split("\",\"city\":\"");
        if (strr.length < 2 && strr.length == 1) {
            //直辖市
            String[] sr = str.split("\"province\":\"");
            String[] srr = sr[1].split("\",\"city");
            return srr[0];
        }
        //非直辖市
        String[] strrr = strr[1].split("\",\"citycode\":");
        return strrr[0];
    }

    /**
     * 获取城市编码
     * @return
     */
    public static String cityCode(String str) {
        //城市切割
        String[] strr = str.split("\",\"citycode\":\"");
        if (strr.length < 2 && strr.length == 1) {
            //直辖市
            String[] sr = str.split("\"province\":\"");
            String[] srr = sr[1].split("\",\"citycode");
            return srr[0];
        }
        //非直辖市
        String[] strrr = strr[1].split("\",\"district\":");
        return strrr[0];
    }

    /**
     * 获取区名称
     * @return
     */
    public static String adName(String str) {
        //城市切割
        String[] strr = str.split("\",\"district\":\"");
        if (strr.length < 2 && strr.length == 1) {
            //直辖市
            String[] sr = str.split("\"province\":\"");
            String[] srr = sr[1].split("\",\"district");
            return srr[0];
        }
        //非直辖市
        String[] strrr = strr[1].split("\",\"adcode\":");
        return strrr[0];
    }

    /**
     * 获取区编码
     * @return
     */
    public static String adCode(String str) {
        //城市切割
        String[] strr = str.split("\",\"adcode\":\"");
        if (strr.length < 2 && strr.length == 1) {
            //直辖市
            String[] sr = str.split("\"province\":\"");
            String[] srr = sr[1].split("\",\"adcode");
            return srr[0];
        }
        //非直辖市
        String[] strrr = strr[1].split("\",\"township\":");
        return strrr[0];
    }

    /**
     *像高德服务发起请求，返回json格式的字符串
     * 逆地理编码
     * @param url 逆地理编码API服务地址
     * @return 返回带有省市区的参数的json格式字符串
     */
    private static String getAddressResponse(String url){
        StringBuffer result=new StringBuffer();
        try {
            URL u=new URL(url);
            URLConnection urlConnection=u.openConnection();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));

            String line;
            while ((line=bufferedReader.readLine())!=null){
                result.append(line);
            }

            bufferedReader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

        return result.toString();
    }

    /**
     *像高德服务发起请求，返回json格式的字符串
     * 地理编码
     * @param url 地理编码API服务地址
     * @return 返回带有对应省市区编码的json格式字符串
     */
    private static String getCodeResponse(String url){
        StringBuffer result=new StringBuffer();
        try {
            URL u=new URL(url);
            URLConnection urlConnection=u.openConnection();//打开连接
            //urlConnection.getInputStream()读取连接的字节流；InputStreamReader（）将字节流转换成字符流；BufferedReader（）将字符流存到缓存区
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));

            String line;
            while ((line=bufferedReader.readLine())!=null){
                result.append(line);
            }

            bufferedReader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

        return result.toString();
    }

    public static void main(String[] args) {
        // String add = getAdd2("116.237191", "31.913839");
        // JSONObject jsonObject = JSONObject.fromObject(add);
        // JSONArray jsonArray = JSONArray.fromObject(jsonObject.getString("addrList"));
        // JSONObject j_2 = JSONObject.fromObject(jsonArray.get(0));
        // String allAdd = j_2.getString("admName");
        // String arr[] = allAdd.split(",");
        // System.out.println("省:" + arr[0] + "\n市:" + arr[1] + "\n区:" + arr[2]);
    }
}
